<template>
    <div class="main-container">
        <div class="sider" :style="{minHeight:height}">
            <div class="logo" :style="{width:collapsed?'80px':'200px'}">
                <img class="logo-img" :style="{width:collapsed?'69px':'200px'}"
                    :src="collapsed ? require('@/assets/logo/8.png'):require('@/assets/logo/1.png')" />
            </div>
            <a-menu :style="{minHeight:height}" class="menuStyle" v-model="selected" mode="inline" :openKeys="currentOpen"
                :inline-collapsed="collapsed" theme="dark" @click="menuClick" @openChange="subMenuChange">

                <template v-for="parent in routes">

                    <a-menu-item v-if="parent.children && parent.children.length===1" :key="parent.children[0].path">
                        <i class="iconfont menu-ico anticon">{{parent.icon}}</i>
                        <span>{{ parent.children[0].meta.title }}</span>
                    </a-menu-item>
                    <a-sub-menu v-else-if="parent.children" :key="parent.path">
                        <div slot="title">
                            <i class="iconfont menu-ico anticon">{{parent.icon}}</i>
                            <span v-if="!collapsed">{{parent.meta.title}}</span>
                        </div>
                        <template v-for="child in parent.children">
                            <a-menu-item :key="child.path">
                                <span>{{ child.meta.title }}</span>
                            </a-menu-item>
                        </template>

                    </a-sub-menu>
                    <a-menu-item v-else="!parent.children" :key="parent.path">
                        <i class="iconfont menu-ico anticon">{{parent.icon}}</i>
                        <span>{{ parent.meta.title }}</span>
                    </a-menu-item>
                </template>
            </a-menu>
        </div>
        <div ref="rightSide" class="right-side">
            <div class="header">
                <a-button class="shink" type="primary" @click="toggleCollapsed">
                    <a-icon :type="collapsed ? 'menu-unfold' : 'menu-fold'" />
                </a-button>
                <div class="header-mid">
                    <div class="system-type" :class="pageType==='platform'&&'system-type-sel'"
                        @click="clickHeaderBtn('platform')">
                        <i class="iconfont">&#xe61d;</i>
                        <span>平台管理</span>
                    </div>
                    <template v-if="userInfo.type==='ORGAN' && userInfo.functionAccredit">
                        <div class="system-type" :class="pageType==='market'&&'system-type-sel'" @click="clickHeaderBtn('market')"
                            v-if="userInfo.functionAccredit.indexOf('营销中心应用')>=0">
                            <i class="iconfont">&#xe670;</i>
                            <span>营销管理</span>
                        </div>
                        <div class="system-type" :class="pageType==='shopMall'&&'system-type-sel'"
                            @click="clickHeaderBtn('shopMall')" v-if="userInfo.functionAccredit.indexOf('商城管理应用')>=0">
                            <i class="iconfont">&#xe65f;</i>
                            <span>商城管理</span>
                        </div>
                    </template>
                    <template v-if="userInfo.type==='PLATFORM'">
                        <div class="system-type" :class="pageType==='market'&&'system-type-sel'"
                            @click="clickHeaderBtn('market')">
                            <i class="iconfont">&#xe670;</i>
                            <span>营销管理</span>
                        </div>
                        <div class="system-type" :class="pageType==='shopMall'&&'system-type-sel'"
                            @click="clickHeaderBtn('shopMall')">
                            <i class="iconfont">&#xe65f;</i>
                            <span>商城管理</span>
                        </div>
                    </template>

                </div>
                <div class="right-menu">
                    <template v-if="$checkPer(['bigScreenDataQuery'])">
                        <div class="large-btn" @click="jumpNew('largeScreen')" v-if="userInfo.type==='PLATFORM'">
                            <i class="iconfont">&#xe670;</i>
                            <div class="large-btn-word">数据大屏</div>
                        </div>
                        <div class="large-btn" @click="jumpNew('agencyLarge')" v-else-if="userInfo.type==='ORGAN'">
                            <i class="iconfont">&#xe670;</i>
                            <div class="large-btn-word">数据大屏</div>
                        </div>
                    </template>

                    <a-popover title="">
                        <a-avatar class="avatar" alt="" :size="32" icon="user"
                            :src="userInfo.headPortrait&&userInfo.headPortrait" />
                        <template slot="content">
                            <span class="logout-text" @click="logout">退出登录</span>
                            <div class="logout-text" @click="resetPass">修改密码</div>
                        </template>
                        <span class="username" v-if="userInfo.name">{{userInfo.name}}</span>
                    </a-popover>
                </div>
            </div>
            <div class="view">
                <cube-breadcrumb type="cube" icon-type="close" :historyRoutes="historyRoutes" :showCloseEach="true"
                    @click="breadcrumbClick" @close="handleClose" @breadcrumbClose="breadcrumbClose"></cube-breadcrumb>
                <router-view />
            </div>
            <ResetPasswordVue :visible="resetPassVisible" @closeModal="() => resetPassVisible = false" />

        </div>
    </div>
</template>

<script>
import router, { generateRoutes, marketRoute, platformRoute, shopMallRoute } from "../router/index";
import cubeBreadcrumb from "@/components/cubeBreadcrumb.vue";
import { getStorageUserInfo, utilLogout } from "@/utils";
import ResetPasswordVue from "@/components/resetPassword.vue";
import { UserModule } from "@/store/modules/userModules";
import { CommonModule } from "@/store/modules/commonModules";
export default {
    components: {
        cubeBreadcrumb,
        ResetPasswordVue,
    },
    name: "Main",
    data() {
        return {
            resetPassVisible: false,
            selected: [],
            height: "",
            collapsed: false,
            routes: [],
            historyRoutes: [],
            defaultOpen: [],
            currentOpen: [],
            userInfo: {},
            pageType: "",
        };
    },

    computed: {
        menuChange() {
            return UserModule.menuChange; //需要监听的属性
        },
    },
    watch: {
        menuChange() {
            let path = this.$route.path;
            this.selected = [path];
            this.currentOpen = [this.getCurrentOpen(this.routes, path)];
            //如果当前点击的路由已经在历史路由中，则不添加
            let arr = this.historyRoutes.filter((item) => item.path == path);
            if (arr.length > 0) {
                return;
            }
            this.checkRouter(path);
        },
    },
    mounted() {
        const pageType = CommonModule.pageType;
        this.pageType = pageType;
        let allRoutes = [];
        if (pageType === "platform") {
            allRoutes = platformRoute.children;
        } else if (pageType === "shopMall") {
            allRoutes = shopMallRoute.children;
        } else if (pageType === "market") {
            allRoutes = marketRoute.children;
        }
        this.routes = generateRoutes(allRoutes);

        this.currentOpen = [this.getCurrentOpen(this.routes)];
        this.selected = [this.$route.path];
        this.checkRouter(this.$route.path);

        this.userInfo = getStorageUserInfo();
        // if(sessionStorage.getItem("tab")){
        //     this.selected = [sessionStorage.getItem("tab")]
        //     this.checkRouter(this.$route.path)
        // }else{
        //     this.selected = [this.$route.path]
        //     this.checkRouter(this.$route.path)
        // }
    },
    methods: {
        // 获取当前展开的菜单
        getCurrentOpen(routeList, pathStr) {
            let path = this.$route.path;
            if (pathStr) path = pathStr;
            for (let i in routeList) {
                const children = routeList[i].children || [];
                for (let j in children) {
                    if (children[j].path === path) return routeList[i].path;
                }
            }
            return "";
        },
        subMenuChange(key) {
            this.currentOpen = key;
            if (key.length > 1) {
                //过滤掉不是当前打开菜单栏的子路由
                let openKeys = this.currentOpen.filter((item) => item == key[key.length - 1]);
                this.currentOpen = openKeys;
            }
        },
        logout() {
            this.$confirm({
                title: "确定要退出登录吗？",
                okText: "确定",
                cancelText: "取消",
                onOk: async () => {
                    utilLogout();
                },
                onCancel: () => {
                    console.log("Cancel");
                },
            });
        },
        toggleCollapsed() {
            this.collapsed = !this.collapsed;
        },
        checkRouter(key) {
            let name = "";
            this.routes.forEach((item) => {
                if (item.children) {
                    item.children.forEach((item) => {
                        if (item.path == key) {
                            name = item.meta.title;
                        }
                    });
                } else {
                    if (item.path == key) {
                        name = item.meta.title;
                    }
                }
            });

            if (this.historyRoutes.length >= 8) {
                this.historyRoutes.splice(0, 1);
            }
            if (!name) return;
            this.historyRoutes.push({
                path: key,
                name: name,
            });
        },
        menuClick(menuPath) {
            const { key } = menuPath;
            if (key === "/largeScreen") {
                const route = this.$router.resolve({
                    name: "largeScreen",
                    // 如果需要在新窗口中打开
                    replace: true,
                });
                // 在新窗口中打开路由
                window.open(route.href, "_blank");
                return;
            }

            this.$router.push(key);
            //如果当前点击的路由已经在历史路由中，则不添加
            let arr = this.historyRoutes.filter((item) => item.path == key);
            if (arr.length > 0) {
                return;
            }
            this.checkRouter(key);
            this.$nextTick(() => {});
        },
        breadcrumbClick(item) {
            this.$router.push(item.path);
            this.selected = [item.path];
            this.currentOpen = [this.getCurrentOpen(this.routes, item.path)];
        },
        handleClose(item, index) {
            // 实现关闭逻辑，更新breadcrumbItems数组
            if (this.$route.path === this.historyRoutes[index].path) {
                const preRoute = this.historyRoutes[index - 1];
                this.$router.push(preRoute.path);
                this.selected = [preRoute.path];
                this.historyRoutes.splice(index, 1);
            } else {
                this.historyRoutes.splice(index, 1);
            }
        },
        breadcrumbClose(key) {
            if (key === "1") {
                this.historyRoutes = [];
            } else {
                //保留当前路由到历史路由数组，删除其他历史路由
                this.historyRoutes = this.historyRoutes.filter((item) => item.path == this.$route.path);
                this.selected = [this.$route.path];
            }
        },
        resetPass() {
            this.resetPassVisible = true;
        },
        clickHeaderBtn(type) {
            if (CommonModule.pageType === type) return;
            this.jump("/" + type);
        },
        jump(url) {
            this.$router.push(url);
        },
        jumpNew(name) {
            const routerInfo = this.$router.resolve({
                name: name, // 路由配置中的name属性
            });
            window.open(routerInfo.href);
        },
    },
};
</script>

<style>
</style>
<style scoped lang="scss">
@import "@/style/commonStyle.scss";
.menuStyle {
    //height: 100%;
}
.logout-text {
    transition: all 0.4s ease-in-out;
    cursor: pointer;
    &:hover {
        color: $menu-color;
    }
}
::v-deep.ant-avatar {
    box-shadow: 0 0 1px 1px #d7d7d7;
    img {
        object-fit: contain !important;
    }
}
.main-container {
    display: flex;
    height: 100%;
    .sider {
        height: 100%;
        background-color: $menu-color;
    }
    .logo {
        transition: 0.1s all;
        background-color: #ffffff;
        padding: 2px;
        display: flex;
        justify-content: center;
        align-items: center;
        height: 73px;
        .logo-img {
            max-width: 180px;
            max-height: 73px;
        }
    }
    .right-side {
        width: 100%;
        display: flex;
        flex-direction: column;
        height: 100%;
        .header {
            background: #ffffff;
            display: flex;
            justify-content: space-between;
            width: 100%;
            height: 73px;
            align-items: center;
            .shink {
                margin-left: 20px;
            }
            .right-menu {
                display: flex;
                align-items: center;
                float: right;
                right: 0;
                top: 0;
                width: auto;
                span {
                    margin: 10px;
                }
                .username {
                    color: #626262;
                    user-select: none;
                    cursor: pointer;
                    min-width: 100px;
                }
            }
        }
        .header-mid {
            flex-grow: 1;
            text-align: left;
            .system-type {
                display: inline-flex;
                margin-left: 50px;
                font-size: 16px;
                color: #6d6d6d;
                align-items: center;
                padding: 15px 10px;
                cursor: pointer;
                &:hover {
                    color: #708fff;
                }
                .iconfont {
                    font-size: 20px;
                    margin-right: 10px;
                }
            }
            .system-type-sel {
                color: #4469f1;
                font-weight: bold;
                border-bottom: solid 3px #4469f1;
            }
        }
        .view {
            flex-grow: 1;
            height: 200px;
            overflow: auto;
        }
    }
    .menu-ico {
        margin-right: 6px;
    }
    .large-btn {
        color: #666;
        cursor: pointer;
        .iconfont {
            margin-right: 0px;
        }
        .large-btn-word {
            display: inline-block;
            margin-left: 5px;
        }
        &:hover {
            color: #708fff;
        }
    }
}
</style>
